import React,{useState, Fragment, useEffect} from "react";
import { withRouter} from "react-router-dom"
import "./Series.scss"
import SeriesItem from "./SeriesItem"
import FilterSeries from "./FilterSeries"
import NullData from "@/components/nullData/NullData"
import PropTypes from "prop-types"
import {getSearchVal} from "@/utils/tool"
function Series(props){
    const {fliterFn,fliterFlg,location }=props,
          {search}=location;
    console.log(getSearchVal("id",search));
    const {result}=JSON.parse(sessionStorage.series),
        formatList=result.reduce((a,item)=>{
            let index=a.findIndex(subItem=>subItem.id==item.levelid)
            if(index==-1){
                a.push({
                    id:item.levelid,
                    label:item.levelname,
                    children:[
                        {
                            ...item
                        }
                    ]
                })
            }else{
                a[index].children.push({...item})
            }
            return a;
        },[])

     const [list,setList]= useState(formatList),
           [query,setQuery]=useState("");
     function queryFn(obj=''){
        const {id='',value=''}=obj;
        if(value){
            setQuery(id)
            setList(formatList.filter(item=>item.id==id))
        }
        fliterFn();
     }
    return(
        <>
            {
                list&&list.length?<div className="car_series">
                    {
                        list.map(item=>
                            (
                                <Fragment key={item.id}>
                                    <div className="tit">{item.label}</div>
                                    <ul>
                                        {item.children?item.children.map(subItem=><SeriesItem key={subItem.id} dataId={subItem.id}  name={subItem.name} sname={subItem.sname} />):''}
                                    </ul>
                                </Fragment>
                            )
                        ) 
                    }
                    </div>:<NullData></NullData>
            }
            {fliterFlg?<FilterSeries show={fliterFlg} checked={query} change={queryFn}></FilterSeries>:''}
        </>
    )
}
Series.defaultProps={
    fliterFn:()=>{},
    fliterFlg:false,
}
Series.propTypes={
    fliterFn:PropTypes.func,
    fliterFlg:PropTypes.bool
}

export default withRouter(Series);